package github.saw96x.config;

import github.saw96x.common.utils.threadpool.ThreadPoolFactoryUtil;
import github.saw96x.registry.zk.util.CuratorUtils;
import github.saw96x.remoting.transport.netty.server.NettyRpcServer;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @author Saw96x
 * @date 2022/3/18 10:00
 */
@Slf4j
public class CustomShutdownHook {
  private static final CustomShutdownHook CUSTOM_SHUTDOWN_HOOK = new CustomShutdownHook();

  public static CustomShutdownHook getCustomShutdownHook() {
    return CUSTOM_SHUTDOWN_HOOK;
  }

  public void clearAll() {
    log.info("addShutdownHook for clearAll");
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
      try {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), NettyRpcServer.PORT);
        CuratorUtils.clearRegistry(CuratorUtils.getZkClient(), inetSocketAddress);
      } catch (UnknownHostException ignored) {
      }
      ThreadPoolFactoryUtil.shutDownAllThreadPool();
    }));
  }
}
